// 蜂窝蜜造平台生成代码，此文件只生成一次，不需要添加到 .beeignore

    package com.fowo.api.service.impl;
    
    import cn.hutool.core.collection.CollUtil;
    import cn.hutool.core.convert.Convert;
    import cn.hutool.core.util.ObjUtil;
    import cn.hutool.core.util.StrUtil;
    import com.alibaba.excel.EasyExcel;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.fowo.api.common.excel.CustomExcelHandler;
    import com.fowo.api.common.model.RException;
    import com.fowo.api.common.util.DateUtils;
    import com.fowo.api.common.util.ResponseUtils;
    import com.fowo.api.entity.ShopInfo;
    import com.fowo.api.entity.Warehouse;
    import com.fowo.api.inventory.entity.InventoryBatchNo;
    import com.fowo.api.inventory.service.impl.InventoryBatchNoServiceImpl;
    import com.fowo.api.mapper.InventoryListDMapper;
    import com.fowo.api.model.inventory.details.*;
    import com.fowo.api.sys.model.SysDictAllItem;
    import com.fowo.api.sys.service.SysDictService;
    import com.fowo.api.util.LocalDateUtils;
    import org.springframework.beans.BeanUtils;
    import org.springframework.stereotype.Service;

    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletResponse;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.stream.Collectors;


/**
    * 库存明细 服务实现类
    */
@Service
public class InventoryDetailsServiceImpl extends InventoryDetailsBaseServiceImpl {
    @Resource
    private SysDictService sysDictService;
    @Resource
    private WarehouseServiceImpl warehouseService;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private InventoryBatchNoServiceImpl inventoryBatchNoService;
    @Resource
    private InventoryListDMapper inventoryListDMapper;

    /**
     * 仓位库存分页
     */
    @Override
    public Page<InventoryDetailsWarehouseInventoryResult> warehouseInventoryPage(InventoryDetailsWarehouseInventoryParams params) {
        params.initSort("p3.id desc", StrUtil.EMPTY);
        List<List<?>> inventoryDetailsWarehouseInventoryResultPage = this.baseMapper.warehouseInventoryPage(params);
        Long total = Convert.toLong(CollUtil.getFirst(CollUtil.get(inventoryDetailsWarehouseInventoryResultPage, 1)), Long.MAX_VALUE);
        List<?> objects = CollUtil.get(inventoryDetailsWarehouseInventoryResultPage, 0);
        List<InventoryDetailsWarehouseInventoryResult> list = Convert.toList(InventoryDetailsWarehouseInventoryResult.class, objects);
        List<SysDictAllItem> scm00018 = sysDictService.getDictItems("SCM00018");
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        List<Warehouse> warehouses = warehouseService.listByIds(list.stream().map(m -> m.getWarehouse_id()).collect(Collectors.toList()));
        List<ShopInfo> shopInfos = shopInfoService.listByIds(list.stream().map(m -> m.getShop_id()).collect(Collectors.toList()));
        list.forEach(x -> {
            if (CollUtil.isNotEmpty(warehouses)) {
                Warehouse byId = CollUtil.findOne(warehouses, f -> StrUtil.equals(x.getWarehouse_id(), Convert.toStr(f.getId())));
                if (ObjUtil.isNotNull(byId)) {
                    x.setWarehouse_name(byId.getName());
                }
            }
            if(CollUtil.isNotEmpty(shopInfos)){
                ShopInfo byId = CollUtil.findOne(shopInfos, f -> StrUtil.equals(x.getShop_id(), Convert.toStr(f.getId())));
                if (ObjUtil.isNotNull(byId)) {
                    x.setShop_name(byId.getShopName());
                }
            }
            List<SysDictAllItem> collect = scm00018.stream().filter(s -> Long.valueOf(s.getItemValue()).intValue() == Integer.parseInt(x.getType())).collect(Collectors.toList());
            x.setType_name(collect.get(0).getItemText());
        });
        Page resultPage = params.toPage();
        resultPage.setTotal(total).setRecords(list);
        return resultPage;
    }


    @Override
    public void WarehouseInventoryExport(Long templateId, InventoryDetailsWarehouseInventoryParams params, HttpServletResponse response) throws Exception {
        if (templateId != null && templateId > 0) {
            throw new RException("暂不支持模版！");
        }

        int current = 1;
        List<InventoryDetailsWarehouseInventoryExcelPo> items = new ArrayList<>();
        while (true) {
            params.setCurrent(current);
            params.setPageSize(EXPORT_QUERY_MAX_SIZE);
            Page<InventoryDetailsWarehouseInventoryResult> page = warehouseInventoryPage(params);
            if (page.getTotal() > EXPORT_MAX_SIZE) {
                throw new RException("导出记录数超出限制！");
            }
            List<InventoryDetailsWarehouseInventoryResult> list = page.getRecords();
            if (list.isEmpty()) {
                break;
            }
            for (InventoryDetailsWarehouseInventoryResult item : list) {
                InventoryDetailsWarehouseInventoryExcelPo excel = new InventoryDetailsWarehouseInventoryExcelPo();
                BeanUtils.copyProperties(item, excel);

                items.add(excel);
            }
            if (list.size() < EXPORT_QUERY_MAX_SIZE) {
                break;
            }
            current++;
        }
        String fileName = String.format("库存明细(%s).xlsx", DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME));
        ResponseUtils.setAttachmentFileName(response, fileName);
        EasyExcel.write(response.getOutputStream())
                .registerWriteHandler(new CustomExcelHandler())
                .sheet()
                .head(InventoryDetailsWarehouseInventoryExcelPo.class)
                .doWrite(items);
    }

    @Override
    public Page<InventoryDetailsWarehouseStockResult> warehouseStockPage(InventoryDetailsWarehouseStockParams params) {
        params.initSort("warehouse.id desc", StrUtil.EMPTY);
        List<List<?>> inventoryDetailsWarehouseStockResultPage = this.baseMapper.warehouseStockPage(params);

        Long total = Convert.toLong(CollUtil.getFirst(CollUtil.get(inventoryDetailsWarehouseStockResultPage, 1)), Long.MAX_VALUE);
        List<?> objects = CollUtil.get(inventoryDetailsWarehouseStockResultPage, 0);
        List<InventoryDetailsWarehouseStockResult> list = Convert.toList(InventoryDetailsWarehouseStockResult.class, objects);
        if (CollUtil.isEmpty(list)) {
            return null;
        }
//        List<Warehouse> warehouses = warehouseService.listByIds(list.stream().map(m -> m.getWarehouse_id()).collect(Collectors.toList()));
//        List<ShopInfo> shopInfos = shopInfoService.listByIds(list.stream().map(m -> m.getShop_id()).collect(Collectors.toList()));

        list.forEach(x -> {
//            if (CollUtil.isNotEmpty(warehouses)) {
//                Warehouse byId = CollUtil.findOne(warehouses, f -> StrUtil.equals(x.getWarehouse_id(), Convert.toStr(f.getId())));
//                if (ObjUtil.isNotNull(byId)) {
//                  //  x.set仓库(byId.getName());
//                }
//            }
//            if(CollUtil.isNotEmpty(shopInfos)){
//                ShopInfo byId = CollUtil.findOne(shopInfos, f -> StrUtil.equals(x.getShop_id(), Convert.toStr(f.getId())));
//                if (ObjUtil.isNotNull(byId)) {
//                    x.setShopName(byId.getShopName());
//                }
//            }
            //15天之前的
            Date date15 = LocalDateUtils.addDateDays(new Date(), -15);
            Long qty = getQty(x.getShop_id(), x.getWarehouse_id(), x.getProduct_id(), x.getFn_sku(), date15, new Date());
            x.setAgeStockAge15(qty != null ? qty.toString() : null);
            Date date16 = LocalDateUtils.addDateDays(new Date(), -16);
            Date date30 = LocalDateUtils.addDateDays(new Date(), -30);
            Long qty2 = getQty(x.getShop_id(), x.getWarehouse_id(), x.getProduct_id(), x.getFn_sku(), date30, date16);
            x.setAgeStockAge30(qty2 != null ? qty2.toString() : null);
            Date date31 = LocalDateUtils.addDateDays(new Date(), -31);
            Date date90 = LocalDateUtils.addDateDays(new Date(), -90);
            Long qty3 = getQty(x.getShop_id(), x.getWarehouse_id(), x.getProduct_id(), x.getFn_sku(), date90, date31);
            x.setAgeStockAge90(qty3 != null ? qty3.toString() : null);
            Date date91 = LocalDateUtils.addDateDays(new Date(), -91);
            Long qty4 = getQty(x.getShop_id(), x.getWarehouse_id(), x.getProduct_id(), x.getFn_sku(), date91, null);
            x.setAgeStockAge91(qty4 != null ? qty4.toString() : null);
//            x.setWarehouseBins(wareBin);
            InventoryDetailsGetBinInventoryParam param = new InventoryDetailsGetBinInventoryParam();
            param.setStockId(x.getWarehouse_id() == null ? null : Long.valueOf(x.getWarehouse_id()));
            param.setShopId(x.getShop_id() == null ? null : Long.valueOf(x.getShop_id()));
            param.setProductId(Convert.toLong(x.getProduct_id()));
            param.setFnSku(x.getFn_sku());
            //设置仓位
            x.setBinArr(inventoryListDMapper.getBinInventory(param));
            //设置采购订单待到货
            x.setPurchaseOrderList(inventoryListDMapper.getPurchaseOrder(param));
        });
        Page resultPage = params.toPage();
        resultPage.setTotal(total).setRecords(list);
        return resultPage;
    }

    Long getQty(String shopId, String Wid, String productId, String fnSku, Date startDate, Date endDate) {
        QueryWrapper<InventoryBatchNo> queryWrapper = new QueryWrapper();
        queryWrapper.select("sum(stock_qty) as  stock_qty");
        queryWrapper.eq("stock_id", Wid);
        queryWrapper.eq("item_id", productId);
        if (shopId != null) {
            queryWrapper.eq("shop_id", shopId);
        } else {
            queryWrapper.isNull("shop_id");
        }
        if (fnSku != null) {
            queryWrapper.eq("fn_sku", fnSku);
        } else {
            queryWrapper.isNull("fn_sku");
        }
        if (startDate != null && endDate != null) {
            queryWrapper.between("create_time", LocalDateUtils.format(startDate, LocalDateUtils.DATE_PATTERN) + " 00:00:00", LocalDateUtils.format(endDate, LocalDateUtils.DATE_PATTERN) + " 23:59:59");
        } else {
            queryWrapper.le("create_time", LocalDateUtils.format(startDate, LocalDateUtils.DATE_PATTERN) + " 23:59:59");
        }
        InventoryBatchNo one = inventoryBatchNoService.getOne(queryWrapper);
        return one != null ? one.getStockQty().longValue() : 0;
    }
}
